package org.neuedu.fly.service;

import org.apache.ibatis.session.SqlSession;
import org.neuedu.fly.entity.Sign;
import org.neuedu.fly.entity.vo.ResponseEntity;
import org.neuedu.fly.mapper.SignMapper;
import org.neuedu.fly.util.SqlSessionUtil;
import org.neuedu.fly.util.TimeUtil;

import java.util.Date;
import java.util.Objects;

public class SignService {
    private SqlSession session = null;
    private SignMapper signMapper = null;

    public ResponseEntity isSign(String uId) {
        session = SqlSessionUtil.getSqlSession();
        signMapper = session.getMapper(SignMapper.class);
        int userId = Integer.parseInt(uId);
        Sign isSign = signMapper.findSignById(userId, new Date());//查询今日是否签到
        Sign signById = signMapper.findSignById(userId, null);//查询签到数据
        if (Objects.nonNull(isSign)) {
            return new ResponseEntity(0, null, "今日已签到", isSign);
        }
        if (Objects.nonNull(signById) && TimeUtil.isTrueTime(signById.getCreateTime(), new Date()) > 1) {
            Sign newSign = Sign.builder().userId(userId).signCount(0).build();
            boolean flag = signMapper.update(newSign);
            session.commit();
            signById = signMapper.findSignById(userId, null);
        }
        return new ResponseEntity(1, null, "今日签到", signById);
    }

    public ResponseEntity doSign(String uId) {
        session = SqlSessionUtil.getSqlSession();
        signMapper = session.getMapper(SignMapper.class);
        int userId = Integer.parseInt(uId);
        Sign sign = signMapper.findSignById(userId, null);
        if (Objects.isNull(sign)) {
            boolean isInsert = signMapper.insert(Sign.builder().userId(userId).signCount(1).build());
            session.commit();
            if (!isInsert) {
                session.rollback();
                return ResponseEntity.error("签到失败！");
            }
        } else {
            int signCount = TimeUtil.isTrueTime(sign.getCreateTime(), new Date()) == 1 ? sign.getSignCount() + 1 : 1;
            Sign newSign = Sign.builder().userId(userId).signCount(signCount).createTime(new Date()).build();
            boolean flag = signMapper.update(newSign);
            session.commit();
            if (!flag) {
                session.rollback();
                return ResponseEntity.error("签到失败！");
            }
        }
        signMapper.signKiss(userId,5);
        session.commit();
        return ResponseEntity.ok("签到成功！");
    }
}